package com.njpi.stu.attendance.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njpi.stu.attendance.entity.CheckWork;
import com.njpi.stu.attendance.entity.CheckWorkLog;
import com.njpi.stu.attendance.entity.TotalData;
import com.njpi.stu.attendance.entity.User;
import com.njpi.stu.attendance.service.ICheckWorkLogService;
import com.njpi.stu.attendance.service.ICheckWorkService;
import com.njpi.stu.attendance.service.IUserService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class LoginController {

    @Autowired
    private ICheckWorkService checkWorkService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICheckWorkLogService checkWorkLogService;


    /**
     * 登录成功后跳转后台首页，更新签到信息
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/home")
    public String flush(Model model, HttpSession session){
        model.addAttribute("title","后台首页");
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_num",name);
        User user = userService.getOne(queryWrapper);
        //System.out.println(user);
        session.setAttribute("user",user);

        //将过期的签到窗口关掉
        List<CheckWork> list = checkWorkService.list();
        for (CheckWork checkWork : list) {
            int compare=checkWork.getTimeEnd().compareTo(new Date());
            if(compare<=0){
                checkWork.setState(0);
                checkWorkService.updateById(checkWork);
                //将已经签到时间已经结束，却还没有签到的人保存为签到的数据
                /**
                 * 1.通过className查找所有该课程的学生名
                 * 2.通过学生名字数组遍历查找记录表有无签到
                 */
                List<String> realNames = userService.getAllRealNames(checkWork.getClassName());
                for (String realName : realNames) {
                    Boolean checked = checkWorkLogService.checkUserChecked(checkWork.getCheckId(), realName);
                    //根据签到id和学生姓名判断该学生有无假条
                    boolean hasLeavNote = checkWorkService.hasLeavNote(checkWork, realName);
                    if(checked){
                        CheckWorkLog checkWorkLog=new CheckWorkLog();
                        checkWorkLog.setUserName(realName);
                        checkWorkLog.setOperator(checkWork.getUserName());
                        if(hasLeavNote){
                            checkWorkLog.setType(2);
                        }else {
                            checkWorkLog.setType(-4);
                        }
                        checkWorkLog.setCourseName(checkWork.getCourseName());
                        checkWorkLog.setCreateTime(new Date());
                        checkWorkLog.setCheckId(checkWork.getCheckId());
                        checkWorkLogService.save(checkWorkLog);
                    }
                }


            }
        }


        //查询签到情况
        QueryWrapper checkQuery=new QueryWrapper();
        Map param=new HashMap<>();
        param.put("state",1);
        if(user.getType()==0){//学生身份
            //查询签到未关闭的记录,本班的记录
            param.put("class_name",user.getClassName());
            //查询已经签到过的，并排除掉
            List<Long> ckeckIdList = checkWorkLogService.selectAllCkeckId(user.getRealName());
            checkQuery.notIn("check_id",ckeckIdList);
        }else if(user.getType()==1){
            //如果身份是老师的话则根据老师姓名查询
            param.put("user_name",user.getRealName());
        }
        checkQuery.allEq(param);
        checkQuery.orderByAsc("time_start");
        IPage page = checkWorkService.page(new Page<>(1,10), checkQuery);
        model.addAttribute("checkWorkList",page.getRecords());


        //查询汇总的数据，通过签到记录
        HashMap<String, TotalData> totalDataHashMap = checkWorkLogService.reportForStu(user.getRealName());
        model.addAttribute("total",totalDataHashMap);

        return "home";
    }

    /**
     * 跳转登录界面
     * @return
     */
    @RequestMapping("/login")
    public String skipLoginPage(){
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return "login";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        return "redirect:/login";
    }


    @RequestMapping("/")
    public String skipHomePage(){
        return "index";
    }



}
